﻿
namespace Leetcode.N0467.V1;

public class Solution
{
    public int FindSubstringInWraproundString(string p)
    {
        var n = p.Length;
        var flgs = new bool[n, 26];
        for (int fromIndex = 0; fromIndex < n; fromIndex++)
        {
            var toIndex = this.FindSubstring(p, fromIndex);
            this.SetFlags(p, fromIndex, toIndex, flgs);
            fromIndex = toIndex;
        }

        return this.Sum(flgs, n);
    }

    private int FindSubstring(string p, int fromIndex)
    {
        var toIndex = fromIndex;
        for (int i = fromIndex + 1; i < p.Length && (p[i] - p[i - 1] + 26) % 26 == 1; i++)
        {
            toIndex = i;
        }
        return toIndex;
    }

    private void SetFlags(string p, int fromIndex, int toIndex, bool[,] flgs)
    {
        var length = toIndex - fromIndex + 1;
        for (int i = 0; i < length; i++)
        {
            for (int j = 0; j < 26 && (i + j) < length; j++)
            {
                flgs[i, p[fromIndex + j] - 'a'] = true;
            }
        }
    }

    private int Sum(bool[,] flgs, int n)
    {
        var sum = 0;
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < 26; j++)
            {
                if (flgs[i, j])
                {
                    sum++;
                }
            }
        }
        return sum;
    }
}